using System;
using System.Windows;
using System.Windows.Navigation;

using DanielVaughan.Services;

namespace DanielVaughan.Calcium.Modules.WebBrowser
{
	public static class WebBrowserUtility
	{
		public static readonly DependencyProperty BindableSourceProperty = DependencyProperty.RegisterAttached(
			"BindableSource", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged));

		public static string GetBindableSource(DependencyObject obj)
		{
			return (string)obj.GetValue(BindableSourceProperty);
		}

		public static void SetBindableSource(DependencyObject obj, string value)
		{
			obj.SetValue(BindableSourceProperty, value);
		}

		//http://stackoverflow.com/questions/263551/databind-the-source-property-of-the-webbrowser-in-wpf
		public static void BindableSourcePropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
		{
			var browser = dependencyObject as System.Windows.Controls.WebBrowser;
			if (browser != null)
			{
				string uri = e.NewValue as string;
				if (string.IsNullOrEmpty(uri))
				{
					return;
				}

				if (!uri.StartsWith("http://") && uri.IndexOf("://") == -1)
				{
					uri = "http://" + uri;
				}

				try
				{
					browser.Source = uri != null ? new Uri(uri) : null;
				}
				catch (UriFormatException)
				{
					var messageService = ServiceLocatorSingleton.Instance.GetInstance<IMessageService>();
					messageService.ShowError("Url format is invalid."); /* TODO: Make localizable resource. */
				}
				
			}
		}

	}
}